package io.github.wanggit.antrpc.gateway.web;

import io.github.wanggit.antrpc.commons.bean.AbstractHttpMethod;
import io.github.wanggit.antrpc.commons.bean.HttpBean;
import io.github.wanggit.antrpc.commons.bean.ParamBean;
import io.github.wanggit.antrpc.commons.utils.JsonUtils;
import io.github.wanggit.antrpc.gateway.starter.IGatewayContext;
import io.github.wanggit.antrpc.gateway.starter.containers.IHttpUrlContainer;
import io.github.wanggit.antrpc.gateway.web.utils.ParameterUtil;
import io.github.wanggit.antrpc.gateway.web.utils.StreamUtil;
import io.github.wanggit.antrpc.gateway.web.vo.Result;
import io.vavr.Tuple3;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping
public class EntrypointController implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @RequestMapping(
            value = "/{appName}/api/**",
            method = {RequestMethod.GET, RequestMethod.POST})
    public Result entrypoint(
            @PathVariable("appName") String appName, HttpServletRequest servletRequest) {
        IGatewayContext gatewayContext = applicationContext.getBean(IGatewayContext.class);
        IHttpUrlContainer httpUrlContainer = gatewayContext.getHttpUrlContainer();
        // 查看是否有对应的参数信息
        if (!httpUrlContainer.contains(
                appName,
                servletRequest.getMethod().toUpperCase(),
                servletRequest.getRequestURI())) {
            return Result.e404();
        }
        Tuple3<HttpBean, AbstractHttpMethod, String> tuple3 =
                httpUrlContainer.find(
                        appName,
                        servletRequest.getMethod().toUpperCase(),
                        servletRequest.getRequestURI());
        if (null == tuple3) {
            return Result.e404();
        }
        // 获取所有请求头信息
        Enumeration<String> headerNames = servletRequest.getHeaderNames();
        Map<String, String> headers = new HashMap<>();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            String headerValue = servletRequest.getHeader(headerName);
            headers.put(headerName, headerValue);
        }
        // URL上的请求参数
        Map<String, Object> parameters =
                new HashMap<>(ParameterUtil.queryStringToMap(servletRequest.getQueryString()));
        // 表单提交的请求参数
        servletRequest
                .getParameterMap()
                .forEach(
                        (key, values) -> {
                            parameters.put(key, values[0]);
                        });
        // 请求体提交的请求参数
        String requestBody = StreamUtil.requestBodyToString(servletRequest);
        Map tmpMap = JsonUtils.fromJson(requestBody, Map.class);
        // TODO 把request body 中的参数添加到Map中

        List<ParamBean> paramBeans = tuple3._2.getParamBeans();
        // TODO 处理参数验证

        return Result.ok();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
